package com.czk.codec;

import com.czk.utils.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/10 11:39
 */
public class ObjectEncode extends MessageToByteEncoder<String> {
    private Class<?> clazz;

    public ObjectEncode(Class<?> clazz) {
        this.clazz = clazz;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, String s, ByteBuf byteBuf) throws Exception {
        if (clazz.isInstance(s)) {
            // 是string类型
            // 转为字节数组
            byte[] serializer = SerializationUtil.serializer(s);
            // 拿到长度
            int length = serializer.length;
            // 写入
            byteBuf.writeInt(length);
            byteBuf.writeBytes(serializer);
        }
    }
}
